import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity, Image, FlatList, TextInput, Alert
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import MethodUtil from '../../../utils/MethodUtil';
import { RangTime } from '../../../component/common/RangTime.js';
const scale = GLOBAL.SCALE;
const uriImg = require('../../../imgs/sanjiao3.png');
export class orderOccupiedList extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		let { orderType } = navigation.state.params || {}
		return {
			headerTitle: (orderType == 'P' ? '采购' : '销售') + '订单占用',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../imgs/goBackEmpty.png')} />),
			headerStyle: {  // 头部整体样式 
				elevation: 0,
				borderBottomWidth: 0,
				backgroundColor: style.color.themeColor
			},
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);
		let { corpType, companyId, corpId, isForeign } = props.navigation.state.params || {}
		this.state = {
			status: 'data',
			refreshIcon: false, // 下拉刷新图标
			listData: [], // 列表数据
			refuseModalVisible: false,
			orderLimitAmt: '',
			showTimeModal: false,
			typesIndex: 2,
			isModal: false,
			isForeign
		}
		this.corpId = corpId
		this.reload = true; // 判断是整个页面刷新还是下拉刷新
		this.totalPage = 1; // 总页数
		this.taskId = '';
		this.pageParams = { // TODO
			pageNo: 1,
			pageSize: 10,
			corpType,
			companyId,
			corpId,
			isForeign
		}
		this.typeData = [
			{
				dictName: '所有订单',
				dictKey: '',
			},
			{
				dictName: '已清账',
				dictKey: 'CLEAR',
			},
			{
				dictName: '未清帐',
				dictKey: 'GENERATE',
			}
		]
	}
	async componentWillMount() {
		await this.initPage();
	}

	async initPage() {
		this.setState({
			status: this.reload ? 'loading' : 'data',
			refreshIcon: !this.reload && this.pageParams.pageNo == '1'
		})
		this.pageParams.recordType = this.typeData[this.state.typesIndex].dictKey
		let res = await HTTP.POST(API_GENERATE(API.CAPITAL_TRANS_LIST), this.pageParams);
		let orderLimitAmt = res.orderLimitAmt
		res = res.PaginationModel
		console.log(res)
		if (res) {
			this.totalPage = res.totalPage;
			this.setState({
				status: res.rows && res.rows.length > 0 ? 'data' : 'empty',
				listData: this.pageParams.pageNo == '1' ? res.rows : this.state.listData.concat(res.rows),
				refreshIcon: false,
				orderLimitAmt: Math.abs(orderLimitAmt)
			})
		} else {
			this.setState({
				refreshIcon: false,
				status: 'error'
			})
		}
	}

	// 刷新页面
	reloadPage = () => {
		this.pageParams.pageNo = 1;
		this.reload = true;
		this.initPage();
	}

	// 下拉刷新
	refresh() {
		this.pageParams.pageNo = 1;
		this.reload = false;
		this.initPage();
	}

	// 上拉翻页
	loadMore() {
		if (this.totalPage > this.pageParams.pageNo) {
			this.pageParams.pageNo++;
			this.reload = false;
			this.initPage();
		}
	}

	_toMoney(num) {
		let { isForeign } = this.state
		let currency = (isForeign !== 1 ? '￥' : '$')
		if (num) {
			let str = MethodUtil.toThousands(num || 0, 2)
			let arr = str.split('')
			if (num > 0) {
				arr.splice(0, 0, currency);
			}
			else {
				arr.splice(1, 0, currency);
			}
			str = arr.join('')
			return str
		}
		else {
			return 0
		}
	}

	//打开时间弹框
	_timeOpen = () => {
		this.setState({
			showTimeModal: true
		})
	}
	// 选择时间
	_resultCall = (resultData) => {
		this.pageParams.beginTime = resultData.startTime || '';
		this.pageParams.endTime = resultData.endTime;
		this.setState({ showTimeModal: false, }, () => {
			this.reloadPage();
		})
	}
	//选择状态 回调函数
	_stateCallBack = (index) => {
		this.setState({
			isModal: false,
			typesIndex: index
		}, () => {
			this.reloadPage();
		})
	}
	//切换功能
	_toggle = (onoff) => {
		this.setState({
			isModal: onoff
		})
	}
	_renderSearchWarp = () => {
		const searchIcon = require('../../../imgs/global/whiteSearch.png');
		return (
			<View style={styles.filterWrap}>
				<View>
					<Image source={searchIcon} style={styles.searchIcon} />
					<TextInput
						ref="orderKeywordsInput"
						style={styles.searchInput}
						underlineColorAndroid='transparent'
						placeholder={"请输入订单号"}
						placeholderTextColor="rgba(255, 255, 255, .8)"
						maxLength={30}
						returnKeyType={'search'}
						defaultValue={this.pageParams.searchKey}
						onChangeText={(txt) => { this.pageParams.searchKey = txt; }}
						onSubmitEditing={() => { this.refresh() }}
					/>
				</View>
			</View>
		)
	}
	// 列表
	_renderListItem = (data, index) => {
		let { isForeign } = this.state
		let { orderId, createTime, amount, status, orderType } = data;
		return (
			<TouchableOpacity activeOpacity={1} onPress={() => {
				this.props.navigation.navigate('occupiedDetail', {
					orderId,
					corpId: this.corpId,
					orderType,
					isForeign
				})
			}} style={[styles.listItem, index == this.state.listData.length - 1 ? { borderBottomWidth: 0 * scale } : null]}>
				<View>
					<Text style={{ marginBottom: 4 * scale, fontSize: 15 * scale, color: '#000' }}>{orderId}</Text>
					<Text style={styles.listItemTime}>{createTime}</Text>
				</View>
				<View style={{ flexDirection: 'row', alignItems: 'center' }}>
					{status == 'COMPLETED' ?
						<Text style={{ fontSize: 16 * scale, color: '#000' }}>已清账</Text> :
						<Text style={[styles.listItemNum, amount > 0 ? { color: '#CA0202', } : { color: '#19977B' }]}>{amount > 0 ? '+' : ''}{this._toMoney(amount)}</Text>
					}
					<Image source={require('../../../imgs/arrow.png')} style={styles.detailImg} />
				</View>
			</TouchableOpacity>
		)
	}

	render() {
		let { status, listData, refreshIcon, showTimeModal, orderLimitAmt, typesIndex, isModal } = this.state;
		return (
			<View style={styles.container}>
				<View style={styles.headBox}>
					{this._renderSearchWarp()}
				</View>
				<View style={styles.fixedBox}>
					<View style={styles.flexRow}>
						{this.pageParams.beginTime ?
							<TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }}
								onPress={this._timeOpen}
							>
								<Text style={styles.statusItemText}>{this.pageParams.beginTime || ''}</Text>
								<Text style={[styles.statusItemText, styles.statusItemTextActive]}>至</Text>
								<Text style={styles.statusItemText}>{this.pageParams.endTime || ''}</Text>
								<Image style={styles.imgStyle} source={uriImg} />
							</TouchableOpacity>
							: <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }}
								onPress={this._timeOpen}>
								<Text style={styles.statusItemText}>所有时间</Text>
								<Image style={styles.imgStyle} source={uriImg} />
							</TouchableOpacity>
						}
						<TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center' }} onPress={() => { this._toggle(true) }}>
							<Text style={styles.statusItemText}>{this.typeData.length > 0 ? this.typeData[typesIndex].dictName : '所有订单'}</Text>
							<Image style={styles.imgStyle} source={uriImg} />
						</TouchableOpacity>
					</View>
					<View style={{ flexDirection: 'row', alignItems: 'center', marginTop: 10 * scale, justifyContent: 'flex-end' }}>
						<Text style={styles.fixedText}>
							订单欠款总额{this._toMoney(orderLimitAmt)}元
            </Text>
					</View>
				</View>
				{
					status == 'data' ? (
						<View style={{ flex: 1, backgroundColor: '#fff', paddingHorizontal: 16 * scale, paddingBottom: 10 * scale }}>
							<FlatList
								data={listData}
								renderItem={({ item, index }) => this._renderListItem(item, index)}
								refreshing={refreshIcon}
								onRefresh={() => { this.refresh() }}
								onEndReachedThreshold={0.1}
								onEndReached={() => { this.loadMore() }}
								showsVerticalScrollIndicator={false}
							/>
						</View>) : null
				}
				{
					status != 'data' ? (<PageStatusIndex status={status} emptyText={'暂无记录'} onErrorPress={this.reloadPage} />) : null
				}
				<Common type="modal" demoData={(
					<Common type="listRadio" selectIndex={typesIndex} title={'选择订单类型'} listData={this.typeData} selectCallBack={this._stateCallBack} />
				)} isVisible={isModal} closeCallballFn={() => { this._toggle(false) }} />
				{
					showTimeModal ? <RangTime isClear={true} isVisible={true} markedDates={null} startTime={this.pageParams.beginTime} endTime={this.pageParams.endTime} closeCall={() => { this.setState({ showTimeModal: false }) }} resultCall={this._resultCall} /> : null
				}
			</View >
		)
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.bgGray,
	},
	headerWrap: {
		backgroundColor: style.color.themeColor,
		paddingLeft: 17 * scale,
		paddingRight: 17 * scale,
		paddingBottom: 20 * scale,
	},
	filterWrap: {
		marginTop: 15 * scale,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		position: 'relative',
	},
	searchInput: {
		height: 38 * scale,
		// flex:1,
		width: 280 * scale,
		// paddingLeft: 42 * scale,
		// paddingRight: 12 * scale,
		backgroundColor: 'rgba(255, 255, 255, .33)',
		flexDirection: 'row',
		justifyContent: 'center',
		alignItems: 'center',
		paddingVertical: 0,
		position: 'relative',
		borderRadius: 8 * scale,
		color: '#fff',
		fontSize: 14 * scale,
		textAlign: 'center'

	},
	searchIcon: {
		width: 22 * scale,
		height: 22 * scale,
		position: 'absolute',
		left: 52 * scale,
		top: 8 * scale,
		zIndex: 9,
		opacity: 0.8,
	},
	billNumWrap: {
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingVertical: 16 * scale,
	},
	circle: {
		width: 36 * scale,
		height: 36 * scale,
		marginRight: 14 * scale,

	},
	nameType: {
		fontSize: 14 * scale,
		color: '#5490EC',
		fontWeight: '600',
		position: 'absolute',
		left: 11 * scale,
		top: 11 * scale
	},
	billInfoWrap: {
		flexDirection: 'column',
		alignItems: 'flex-start',
		justifyContent: 'flex-start',
		paddingLeft: 14 * scale,
		paddingRight: 14 * scale,
		paddingTop: 24 * scale,
		borderStyle: 'solid',
		borderBottomColor: '#E3E7F0',
		borderBottomWidth: 1 * scale,
		paddingBottom: 18 * scale
	},
	commonTitle: {
		flex: 1,
		color: '#708090',
		fontSize: 12 * scale,
		minWidth: 64 * scale,
	},
	commonTitleTop: {
		flex: 1,
		fontWeight: '600',
		color: '#000',
		fontSize: 14 * scale,
		minWidth: 64 * scale,
	},
	commonTopRight: {
		fontSize: 12 * scale,
		marginTop: 8 * scale,
		color: '#34475F',
	},
	commonText: {
		flex: 1,
		fontSize: 13 * scale,
		color: '#0C0C0D',
		fontWeight: '700',
		paddingTop: 8 * scale,
	},
	buttonPass: {
		width: 68 * scale,
		backgroundColor: style.color.themeColor,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		marginRight: 14 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
	},
	buttonPassText: {
		color: '#fff',
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	buttonRefuse: {
		width: 68 * scale,
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		marginBottom: 12 * scale,
		borderRadius: 16 * scale,
		borderColor: style.color.themeColor,
		borderWidth: 1,
		marginRight: 14 * scale,
	},
	buttonRefuseText: {
		color: style.color.themeColor,
		fontSize: 12 * scale,
		fontWeight: '700',
		textAlign: 'center'
	},
	titleText: {
		color: '#000',
		marginBottom: 10 * scale,
		fontSize: 14 * scale,
		fontWeight: '600'
	},
	buttonBox: {
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'space-between',
		marginTop: 10 * scale,
	},
	buttonRightBox: {
		flexDirection: 'row',
		// alignItems: 'center',
		justifyContent: 'center',
		marginTop: 5 * scale
	},
	accountSelect: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	},
	billNumWrapTop: {
		flexDirection: 'row',
		alignItems: 'center',
		// justifyContent: 'space-between',
		// marginBottom:11*scale
	},
	buttonLeftText: {
		fontSize: 12,
		color: '#0E7FFD',
	},
	buttonLeftPass: {
		paddingVertical: 10 * scale,
		paddingHorizontal: 20 * scale,
		marginTop: -8 * scale
	},
	topRight: {
		fontSize: 14 * scale,
		color: '#fff',
		marginRight: 10 * scale
	},
	searchBox: {
		width: 330 * scale
	},
	headBox: {
		height: 75 * scale,
		backgroundColor: style.color.themeColor,
		// justifyContent:'center',
		alignItems: 'center'
	},
	listItem: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center',
		height: 69 * scale,
		borderBottomColor: '#E7E7E7',
		borderBottomWidth: 1 * scale,

	},
	listItemTime: {
		fontSize: 10 * scale,
		color: '#000',
		opacity: 0.5,
	},
	listItemNum: {
		fontSize: 15 * scale,
		fontWeight: '600'
	},
	detailImg: {
		width: 6 * scale,
		height: 9 * scale,
		tintColor: '#000',
		marginLeft: 10 * scale
	},
	fixedBox: {
		padding: 15 * scale,
		backgroundColor: style.color.bgGray,
	},
	flexRow: {
		flexDirection: 'row',
		justifyContent: 'space-between',
		alignItems: 'center'
	},
	statusItemText: {
		fontSize: 12 * scale,
		color: '#000'
	},
	statusItemTextActive: {
		paddingLeft: 3 * scale,
		paddingRight: 3 * scale
	},
	imgStyle: {
		width: 12 * scale,
		height: 12 * scale,
		tintColor: '#000',
		marginLeft: 11 * scale,
		// marginTop:2*scale,
		transform: [{ 'rotate': '90deg' }]
	},
	fixedText: {
		fontSize: 12 * scale,
		color: '#657AB0',

	},
})